import { Upload, UploadFile, UploadProps } from "antd";
import { useState } from "react";
import { tonmi } from "tonmi";
function arrayBufferToBase64Image(arrayBuffer: ArrayBuffer, mimeType = 'image/png') {
  // 创建Uint8Array视图来操作ArrayBuffer
  const uint8Array = new Uint8Array(arrayBuffer);
  // 将每个字节转换为对应的字符
  let binaryString = '';
  for (let i = 0; i < uint8Array.length; i++) {
    binaryString += String.fromCharCode(uint8Array[i]);
  }
  // 使用btoa进行Base64编码，并组合成Data URL
  const base64 = btoa(binaryString);
  return `data:${mimeType};base64,${base64}`;
}
export default function HomePage(props: any) {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [uploading, setUploading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>("");
  
  const __props: UploadProps = {
    onRemove: (file) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: (file) => {
      setFileList([]);
      setUploading(true);
      setFileList([]);
      file.arrayBuffer().then(buf => {
        const uri = arrayBufferToBase64Image(buf, 'image/png');
        setImageUrl(uri);

        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/png2ico', true); 
        xhr.responseType = 'blob'; 
        const formData = new FormData();
        formData.append('png', tonmi.Base64EncodeBytes(Array.from(new Uint8Array(buf))));
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) { // 请求完成
            if (xhr.status === 200) {
              setUploading(false);
              const blob = this.response;
              
              const downloadUrl = window.URL.createObjectURL(blob);
              const a = document.createElement('a');
              a.style.display = 'none';
              a.href = downloadUrl;
              
              const contentDisposition = xhr.getResponseHeader('Content-Disposition');
              let fileName = 'a.ico'; // 默认文件名
              if (contentDisposition) {
                  const fileNameMatch = contentDisposition.match(/filename="?([^"]+)"?/);
                  if (fileNameMatch && fileNameMatch[1]) {
                      fileName = fileNameMatch[1];
                  }
              }
              a.download = fileName; 
              
              document.body.appendChild(a);
              a.click();
              
              window.URL.revokeObjectURL(downloadUrl);
              document.body.removeChild(a);
            }
            else {
              setImageUrl("");
              setUploading(false);
            }
          }
        };
        xhr.onerror = function () {
          setImageUrl("");
          setUploading(false);
        };
        xhr.send(formData);
      });
      return false;
    },
    fileList,
  };
  const uploadButton = (
    <div style={{ marginTop: 8 }}>{uploading ? <>上传中</> : <>上传</>}</div>
  );
  return (<div>
    <Upload listType="picture-card" style={{height:"128px", width:"128px",background:"#fff"}} showUploadList={false} {...__props}>
      {imageUrl ? <img draggable={false} src={imageUrl} style={{ width: '100%' }} />:uploadButton}
    </Upload>
  </div>);
}